<template>
  <div class="app-container" ref="appcontainer">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="优惠劵名称" prop="couponName">
        <el-input
          v-model="queryParams.couponName"
          placeholder="请输入优惠劵名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="是否新人劵" prop="newUserState">-->
<!--        <el-select v-model="queryParams.newUserState" placeholder="请选择是否新人劵" clearable size="small">-->
<!--          <el-option-->
<!--            v-for="dict in newUserStateOptions"-->
<!--            :key="dict.dictValue"-->
<!--            :label="dict.dictLabel"-->
<!--            :value="dict.dictValue"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="是否固定有效期" prop="fixedTimeState">
        <el-select v-model="queryParams.fixedTimeState" placeholder="请选择是否固定有效期" clearable size="small">
          <el-option
            v-for="dict in fixedTimeStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon=""
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shopping:mallCoupons:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          :disabled="single"
          @click="handleExamine"
          v-hasPermi="['shopping:mallCoupons:edit']"
        >查看</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shopping:mallCoupons:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['shopping:mallCoupons:export']"
          v-if="false"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :height="tableHeight" :data="mallCouponsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" show-overflow-tooltip />
      <el-table-column label="优惠劵名称" align="center" prop="couponName" />
      <el-table-column label="优惠券金额" align="center" prop="money" />
      <el-table-column label="满多少元可用" align="center" prop="minPrice" />
      <el-table-column label="是否限量" align="center" prop="limitedState">
        <template slot-scope="scope">
          <dict-tag :options="limitedStateOptions" :value="scope.row.limitedState"/>
        </template>
      </el-table-column>
      <el-table-column label="发送数量" align="center" prop="total" />
<!--      <el-table-column label="是否新人劵" align="center" prop="newUserState">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="newUserStateOptions" :value="scope.row.newUserState"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="类型" align="center" prop="couponType">
        <template slot-scope="scope">
          <dict-tag :options="couponTypeOptions" :value="scope.row.couponType"/>
        </template>
      </el-table-column>
      <el-table-column label="是否固定有效期" align="center" prop="fixedTimeState">
        <template slot-scope="scope">
          <dict-tag :options="fixedTimeStateOptions" :value="scope.row.fixedTimeState"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
         <el-button
          size="mini"
          type="text"
          @click="handleExamine(scope.row)"
          v-hasPermi="['shopping:mallCoupons:edit']"
        >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shopping:mallCoupons:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleCreateCdk(scope.row)"
            v-hasPermi="['shopping:mallCoupons:edit']"
          >批量生成兑换码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
        <el-form-item label="优惠劵名称" prop="couponName">
          <el-input v-model="form.couponName" placeholder="请输入优惠劵名称" />
        </el-form-item>
        </el-row>
        <el-row>
            <el-col :span="12">
        <el-form-item label="优惠券金额" prop="money">
          <el-input v-model="form.money" type="number" step="0.01" placeholder="请输入优惠券金额"/>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="满多少元可用" prop="minPrice">
          <el-input v-model="form.minPrice" type="number" step="0.01" placeholder="请输入满多少元可用"/>
        </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否限量">
          <el-radio-group v-model="form.limitedState">
            <el-radio
              v-for="dict in limitedStateOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="发送数量" prop="total" v-if="this.form.limitedState =='Y'">
          <el-input v-model="form.total" placeholder="请输入限量情况下发送数量" />
        </el-form-item>

<!--        <el-form-item label="是否新人券">-->
<!--          <el-radio-group v-model="form.newUserState">-->
<!--            <el-radio-->
<!--              v-for="dict in newUserStateOptions"-->
<!--              :key="dict.dictValue"-->
<!--              :label="dict.dictValue"-->
<!--            >{{dict.dictLabel}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-row>
<!--          分类-->
          <el-form-item label="类型" prop="couponType">
            <el-select v-model="form.couponType" placeholder="请选择类型" @change="changeStatus">
              <el-option
                v-for="dict in couponTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
        <el-col :span="12" v-if="form.couponType == 'classify'">
            <el-form-item label="分类" prop="primaryKey">
              <el-cascader
                placeholder="请选择分类名称"
                v-model="form.primaryKey"
                :options="options"
                :props="countryObj"
                :show-all-levels="false"
                :clearable = "true"
                @change="handleChange"
                ref="cascader"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>


  <el-row :gutter="20">
    <el-col :span="12" v-if="form.couponType == 'product'" >
      <el-form-item label="选择的商品名称">
        <el-input v-model="changeName"  />
      </el-form-item>
    </el-col>
    <el-col :span="6" v-if="form.couponType == 'product'" >
      <el-button
        type="primary"
        plain
        icon=""
        size="mini"
        @click="handleChangeGoods"
        v-hasPermi="['shopping:mallCoupons:add']"
      >选择商品</el-button>
    </el-col>
    </el-row>

        <el-form-item label="可领取时间" prop="receiveStartTime">
                    <el-date-picker clearable size="small"
                                    v-model="getValueTime"
                                    type="datetimerange"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期">
                    </el-date-picker>
       </el-form-item>
        <el-form-item label="是否固定有效期" prop="fixedTimeState">
          <el-select v-model="form.fixedTimeState" placeholder="请选择是否固定有效期">
            <el-option
              v-for="dict in fixedTimeStateOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可使用时间" prop="useStartTime" v-if="this.form.fixedTimeState =='N'">
          <el-date-picker clearable size="small"
                          v-model="getScopeTime"
                          type="datetimerange"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-row>
          <el-col :span="12">
        <el-form-item label="有效期天数" prop="validDay" v-if="this.form.fixedTimeState =='Y'">
          <el-input v-model="form.validDay" placeholder="请输入有效期天数" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" type="number" placeholder="请输入排序" />
        </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <!--%%-->
      <!--    商品券-->
      <el-dialog  v-if="form.couponType == 'product'":close-on-click-modal="false" :title="titleGood" :visible.sync="goodOpen" width="800px" append-to-body>
        <el-form :model="queryProducParams" ref="queryProducParams" :inline="true" v-show="showSearchProduct" label-width="68px">
          <el-form-item label="商品名称" prop="productName">
            <el-input
              v-model="queryProducParams.productName"
              placeholder="请输入商品名称"
              clearable
              size="small"
              @keyup.enter.native="handleQueryProduct"
            />
          </el-form-item>
          <el-form-item label="分类名称" prop="classifyName">
            <el-cascader
              v-model="queryProducParams.classifyCodingName"
              :options="options"
              :props="countryObj1"
              :show-all-levels="true"
              clearable
              placeholder="请选择分类"
              @keyup.enter.native="handleQueryProduct"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryProduct">搜索</el-button>
<!--            <el-button icon="el-icon-refresh" size="mini" @click="resetQueryProduct">重置</el-button>-->
          </el-form-item>
        </el-form>
        <el-row>
        <right-toolbar :showSearch.sync="showSearchProduct" @queryTable="getProductList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :height="tableHeight" :data="mallProductList" @selection-change="handleChangeProduct">
          <el-table-column type="selection" width="55" align="center" show-overflow-tooltip />
          <el-table-column label="商品名称" align="center" prop="productName" />
          <el-table-column label="商品主图" align="center" prop="productImage">
            <template width="120" slot-scope="scope">
              <img style="width:60px;height:60px;border:none;" :src="scope.row.productImage">
            </template>
          </el-table-column>
          <el-table-column label="分类名称" align="center" prop="classifyName" />
          <el-table-column label="原价" align="center" prop="oldPrice" />
          <el-table-column label="售价" align="center" prop="currentPrice" />
          <el-table-column label="销量" align="center" prop="salesNum" />
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="ProductCancel">确 定</el-button>
          <el-button @click="ProductCancel">取 消</el-button>
        </div>
        <pagination
          v-show="productTotal>0"
          :total="productTotal"
          :page.sync="queryProducParams.pageNum"
          :limit.sync="queryProducParams.pageSize"
          @pagination="getProductList"
        />
      </el-dialog>
    </el-dialog>
    <!-- 查看但是不能修改的对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="viewOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-form-item label="优惠劵名称" prop="couponName" >
            <el-input v-model="form.couponName" placeholder="请输入优惠劵名称" disabled/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="优惠券金额" prop="money">
              <el-input v-model="form.money" type="number" step="0.01" placeholder="请输入优惠券金额" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="满多少元可用" prop="minPrice">
              <el-input v-model="form.minPrice" type="number" step="0.01" placeholder="请输入满多少元可用" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否限量" >
          <el-radio-group v-model="form.limitedState" disabled>
            <el-radio
              v-for="dict in limitedStateOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="是否新人券">-->
<!--          <el-radio-group v-model="form.newUserState" disabled>-->
<!--            <el-radio-->
<!--              v-for="dict in newUserStateOptions"-->
<!--              :key="dict.dictValue"-->
<!--              :label="dict.dictValue"-->
<!--            >{{dict.dictLabel}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-row>
          <el-form-item label="类型" prop="couponType">
            <el-select v-model="form.couponType" placeholder="请选择类型" disabled>
              <el-option
                v-for="dict in couponTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
<!--          zhangbo-->
          <el-col :span="12" v-if="form.couponType == 'product'">
          <el-form-item label="商品分类名称">
            <el-input v-model="form.systematicName" disabled/>
          </el-form-item>
        </el-col>
          <el-col :span="12" v-if="form.couponType == 'classify'">
            <el-form-item label="分类名称分类">
              <el-input v-model="form.systematicName" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发送数量" prop="total" v-if='form.limitedState=="Y"'>
              <el-input v-model="form.total" placeholder="请输入限量情况下发送数量" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余数量" prop="lastTotal" v-if='form.limitedState=="Y"'>
              <el-input v-model="form.lastTotal" placeholder="请输入剩余数量"disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可领取时间" prop="receiveStartTime">
              <el-date-picker clearable size="small"
                              v-model="getValueTime"
                              type="datetimerange"
                              disabled
                              format="yyyy-MM-dd HH:mm:ss"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="可领取结束时间" prop="receiveEndTime">-->
<!--              <el-date-picker clearable size="small"-->
<!--                              v-model="form.receiveEndTime"-->
<!--                              type="date"-->
<!--                              value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                              disabled-->
<!--                              placeholder="选择可领取结束时间">-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
          </el-col>
        </el-row>
        <el-form-item label="是否固定有效期" prop="fixedTimeState">
          <el-select v-model="form.fixedTimeState" placeholder="请选择是否固定有效期" disabled>
            <el-option
              v-for="dict in fixedTimeStateOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可使用时间" prop="useStartTime" v-if="this.form.fixedTimeState =='N'">
              <el-date-picker clearable size="small"
                              v-model="getScopeTime"
                              type="datetimerange"
                              disabled
                              value-format="yyyy-MM-dd HH:mm:ss"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="可使用时间范围结束时间" prop="useEndTime">-->
<!--              <el-date-picker clearable size="small"-->
<!--                              v-model="form.useEndTime"-->
<!--                              type="date"-->
<!--                              value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                              disabled-->
<!--                              placeholder="选择可使用时间范围结束时间">-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="有效期天数" prop="validDay" >
              <el-input v-model="form.validDay" placeholder="请输入有效期天数" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" type="number" placeholder="请输入排序" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
<!--    //批量生成兑换码弹出框 -->
    <el-dialog :close-on-click-modal="false" :title="redeemCode" :visible.sync="redeemOpen" width="600px" append-to-body>
      <el-form ref="redeemCodeValue" :model="redeemCodeValue" :rules="rules" label-width="140px">
        <el-form-item label="生成兑换码前三位" prop="cdKey">
         <el-input v-model="redeemCodeValue.cdKey" v-Alphabet placeholder="请输入兑换码前三位字母" maxlength="3" @input="codeInput" />
        </el-form-item>
        <el-form-item label="生成兑换码数量" prop="cdKeyNumber" >
          <el-input v-model="redeemCodeValue.cdKeyNumber" placeholder="请填写兑换码生成的数量"  />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="exportLoading" @click="submitCdk">确 定</el-button>
        <el-button @click="CancelCdk">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listMallCoupons, getMallCoupons, logicDelMallCoupons, addMallCoupons, updateMallCoupons, exportMallCoupons } from "@/api/shopping/mallCoupons";
  import {liststate} from "@/api/shopping/classify";
  import {createCdk} from "@/api/shopping/mallCdk";
  import {goodName,listMallProduct} from "@/api/shopping/mallProduct";
  import Item from "../../../layout/components/Sidebar/Item";
    const checkData= (rule, value, callback) =>{
      if (value) {
        if (/[\u4E00-\u9FA5]/g.test(value)) {
          callback(new Error('不能包含中文!'))
        } else {
          callback()
        }
      }
      callback()
    }


  export default {
    name: "MallCoupons",
    data() {
      return {
        //选择可领取的开始时间和结束时间
        getValueTime:[],
        //可使用时间范围开始时间
        getScopeTime:[],
        //多选的商品名称
        temp:"",
        //分类选中的节点
        classifyNames:[],
        classifyIds:[],
        // 类型字典
        couponTypeOptions: [],
        //选中多个商品查看回显的选中的商品名称
        changeName:"",
        //品类选中回显的名称
        changeClasifyName:"",
        classifyCodingName:[],
        //查询商品信息
        mallProductList:[],
        defaultProps: {
          children: "children",
          label: "classifyName"
        },
        //商品多选
        getProducids:[],
        getproducidgood:[],
        //获取二级分类名称信息
        secondCassifyOptions:[],
        //获取商品信息
        ProductOption:[],
        options:[],
        tableHeight:0,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        //选中多个商品id数组
        idss:[],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: false,
        showSearchProduct:false,
        // 总条数
        total: 0,
        productTotal:0,
        // 优惠券表格数据
        mallCouponsList: [],
        // 弹出层标题
        title: "",
        titleGood:"选择商品",
        redeemCode:"",
        // 是否显示弹出层
        open: false,
        viewOpen:false,
        goodOpen:false,
        redeemOpen:false,
        // 是否限量字典
        limitedStateOptions: [],
        // 是否新人劵字典
        newUserStateOptions: [],
        // 是否一级分类字典
        isFirstClassifyOptions: [],
        // 是否固定有效期字典
        fixedTimeStateOptions: [],
        //兑换码
        redeemCodeValue:{
          cdKey:null,
          cdKeyNumber:null,
          couponId:null,
          limitedState:null,
          lastTotal: null,
        },
        //商品查询参数
        queryProducParams:{
          pageNum: 1,
          pageSize: 10,
          classifyCodingName:null,
          productName:null,
          isShow:"Y",
        },
        // 查询参数
        queryParams: {
          distinctionCdkCoupon:"cdk",
          pageNum: 1,
          pageSize: 10,
          couponName: null,
          systematicName:null,
          money: null,
          minPrice: null,
          limitedState:null,
          total: null,
          lastTotal: null,
          newUserState: null,
          couponType: null,
          primaryKey: null,
          isFirstClassify: null,
          classifyId: null,
          receiveStartTime: null,
          receiveEndTime: null,
          fixedTimeState: null,
          useStartTime: null,
          useEndTime: null,
          validDay: null,
          sort: null,
        },

        // 表单参数
        form: {},
        // 表单校验
          rules: {
          //输入兑换码的前三位
          cdKey :[
            { required: true, message: '请输入兑换码前三位(大小写字母和数字)', trigger: 'blur' },
            { validator: checkData, trigger: 'blur' },
          ],
          //输入兑换码的数量
          cdKeyNumber:[
            { required: true, message: '请输入生成兑换码的数量', trigger: 'blur' },
          ],
          getScopeTime:[
            { required: true, message: '选择时间', trigger: 'blur' }
          ],
          couponName: [
            { required: true, message: '请填写名称', trigger: 'blur' }
          ],
          money: [
            { required: true, message: "优惠券金额不能为空", trigger: "blur" }
          ],
          minPrice: [
            { required: true, message: "满多少元可用不能为空", trigger: "blur" }
          ],
          limitedState: [
            { required: true, message: "是否限量不能为空", trigger: "blur" }
          ],
          total: [
            { required: true, message: "限量数不能为空", trigger: "blur" }
          ],
          // newUserState: [
          //   { required: true, message: "是否新人券不能为空", trigger: "blur" }
          // ],
          couponType: [
            { required: true, message: "优惠券类型不能为空", trigger: "change" }
          ],
          primaryKey: [
            { required: true, message: "关联的分类不能为空", trigger: "blur" }
          ],

          fixedTimeState: [
            { required: true, message: "是否固定有效期不能为空", trigger: "change" }
          ],
          sort: [
            { required: true, message: "排序不能为空", trigger: "blur" }
          ],
          state: [
            { required: true, message: "启用状态不能为空", trigger: "blur" }
          ],

        },
        countryObj:{
          value:'id',
          label: 'classifyName',
          children: 'children',
          multiple: true  ,
          lazy: true,
          lazyLoad (node, resolve) {
            const { level } = node;
            let id = node.value;
            let param={id:id};
            liststate(param).then(response => {
              let options = response.rows;
              debugger
              this.getValue = options
              resolve(options);
            });
          }
        },
        countryObj1:{
          value:'id',
          label: 'classifyName',
          children: 'children',
          lazy: true,
          lazyLoad (node, resolve) {
            const { level } = node;
            let id = node.value;
            let param={id:id};
            liststate(param).then(response => {
              let options = response.rows;
              this.getValue = options
              resolve(options);
            });
          }
        },
      };
    },
    created() {
      this.getList();
      this.calHeight()
      this.getDicts("sys_yes_no").then(response => {
        this.limitedStateOptions = response.data;
      });
      this.getDicts("sys_yes_no").then(response => {
        this.newUserStateOptions = response.data;
      });
      this.getDicts("jy_coupon_type").then(response => {
        this.couponTypeOptions = response.data;
      });
      this.getDicts("sys_yes_no").then(response => {
        this.isFirstClassifyOptions = response.data;
      });
      this.getDicts("sys_yes_no").then(response => {
        this.fixedTimeStateOptions = response.data;
      });
    },
    watch: {
      'showSearch':'calHeight',
      'showSearchProduct':'calHeight'
    },
    methods: {
      //选择商品按钮，方便二次选择商品
      handleChangeGoods(){
        this.goodOpen = true;
      },
      //填写兑换码前三位必须是大小写字母和数字
      codeInput(val) {
        val = val.replace(
          /[\u4E00-\u9FA5]|[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
          ""
        );
        this.redeemCodeValue.cdKey = val;     //    不要忘了把校验之后的值赋值给表单这一项
      },


      //兑换码确定按钮
      submitCdk(){
        if (this.redeemCodeValue.limitedState =="Y"&&this.redeemCodeValue.cdKeyNumber > this.redeemCodeValue.lastTotal&&this.redeemCodeValue.lastTotal!="0"){
          this.msgError("优惠券有数量限制，最多"+this.redeemCodeValue.lastTotal+"个");
          return
        }else if (this.redeemCodeValue.lastTotal=="0"){
          this.msgError("优惠券剩余数量已空,无法生成兑换码!");
          return
        }else if (this.redeemCodeValue.cdKey.length < 3){
          this.msgError("输入错误,请按要求填写信息！")
          return
        }
          this.$refs["redeemCodeValue"].validate(valid => {
            if (valid) {
              this.loading = true;
              if (this.loading = true){
                this.msgSuccess("正在生成中,请等待！")
                this.exportLoading = true;
              }
              createCdk(this.redeemCodeValue).then(response => {
                this.msgSuccess("成功生成");
                this.redeemOpen = false;
                this.exportLoading = false;
                this.getList();
                });
            }
          });
      },
      //兑换码取消按钮
      CancelCdk(){
        this.redeemOpen = false;
        this.reset();
      },
      //批量生成兑换码
      handleCreateCdk(row){
        this.reset();
        this.redeemOpen = true;
        this.redeemCode = "批量生成兑换码"
        this.redeemCodeValue.couponId = row.id;
        this.redeemCodeValue.limitedState = row.limitedState;
        this.redeemCodeValue.lastTotal = row.lastTotal;

      },

      changeStatus(){
        if (this.form.couponType == 'product'){
          this.goodOpen=true;
          this.getProductList();
        }
      },
      //类型是商品券是后查询所有上架的商品信息
      getProductList(){
        if (this.queryProducParams.classifyCodingName!=null){
          let str = this.queryProducParams.classifyCodingName
          if(str.constructor== Array ){
            this.queryProducParams.classifyCodingName = str.join(",")
          }
        }
        listMallProduct(this.queryProducParams).then(response => {
          this.mallProductList = response.rows;
          this.productTotal = response.total;
        });
      },
      //多选商品
      handleChangeProduct(selection){
        this.idss = selection.map(item => item.id)
        this.temp =selection.map(item => item.productName)
        this.changeName =  this.temp.join(",")
      },
        handleChange(value) {
          let node=this.$refs['cascader'].getCheckedNodes(true)
          //获得多选的分类节点
          this.classifyNames = node.map(item=> item.label)//回显的分类名称
          this.classifyIds = node.map(item=> item.value)//分类的id
      },
      calHeight () {
        this.$nextTick(() => {
          const rect = this.$refs.appcontainer.getBoundingClientRect();
          let height= this.$refs.queryForm.$el.offsetHeight;
          this.tableHeight = rect.height-height-120;
        })
      },
      /** 查询优惠券列表 */
      getList() {
        this.loading = true;
        listMallCoupons(this.queryParams).then(response => {
          this.mallCouponsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      //商品券弹窗确认和取消
      ProductCancel() {
        this.goodOpen=false;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.viewOpen = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.redeemCodeValue={
          cdKey:null,
          cdKeyNumber:null,
          couponId:null,
        },
        this.queryProduc = {
          productName :null,
          classifyCodingName :null,
        } ,
        this.form = {
          distinctionCdkCoupon:null,
          parentId:null,
          id: null,
          couponName: null,
          money: null,
          minPrice: null,
          limitedState: "N",
          total: null,
          lastTotal: null,
          newUserState:"N",
          couponType: "general",
          primaryKey: null,
          isFirstClassify: null,
          classifyId: null,
          receiveStartTime: null,
          receiveEndTime: null,
          fixedTimeState: null,
          useStartTime: null,
          useEndTime: null,
          validDay: null,
          sort: 1,
          delState: null,
          delUser: null,
          delType: null,
          delTime: null,
          createBy: null,
          createType: null,
          createTime: null,
          updateBy: null,
          updateType: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 商品搜索按钮操作 */
      handleQueryProduct(){
        this.queryProducParams.pageNum = 1;
        this.getProductList();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.showSearch=false;
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 商品重置按钮操作 */
      resetQueryProduct(){
        this.reset();
        this.queryProducParams.classifyCodingName=null;
        this.queryProducParams.productName=null;
        this.handleQueryProduct();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 查看按钮操作 */
      handleExamine(row){
        this.reset();
        const query = {
          id:row.id || this.ids.toString()
        }
        getMallCoupons(query).then(response => {
          this.form = response.data;
          this.getValueTime[0]=this.form.receiveStartTime;///可领取开始时间
          this.getValueTime[1]=this.form.receiveEndTime;//可领取结束时间
          if(this.form.fixedTimeState =='N'){
            this.getScopeTime[0]=this.form.useStartTime;//可使用时间范围开始时间
            this.getScopeTime[1]=this.form.useEndTime; //可使用时间范围结束时间
          }
          this.viewOpen = true;
          this.title = "查看优惠券";
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getList();
        this.getValueTime=[];
        this.getScopeTime=[];
        this.open = true;
        this.title = "添加优惠券";
      },
      /** 提交按钮 */
      submitForm() {
        if (this.getValueTime==[]){
          this.msgError("请选择可领取时间")
          return
        }
        if (this.getScopeTime==[]&& this.form.fixedTimeState =='N'){
          this.msgError("请选择可使用时间")
          return;
        }
          this.form.receiveStartTime = this.getValueTime[0];//可使用时间范围开始时间
          this.form.receiveEndTime = this.getValueTime[1];//可使用时间范围结束时间
        if (this.form.fixedTimeState =='N'){
          this.form.useStartTime = this.getScopeTime [0];//可领取开始时间
          this.form.useEndTime = this.getScopeTime[1];//可领取结束时间
        }
        if (this.form.couponType=='product'){
          this.form.primaryKey =","+this.idss.join(",")+",";
        }
        if (this.form.couponType=='classify'){
         this.form.primaryKey = ","+this.classifyIds.join(",")+",";
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateMallCoupons(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.distinctionCdkCoupon = "cdk";
              addMallCoupons(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.getValueTime = [];
                this.getScopeTime = [];
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return logicDelMallCoupons(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm("是否确认导出+"+"优惠券数据项?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportMallCoupons(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
      }
    }
  };
</script>
